//
//  MineViewController.m
//  myCar
//
//  Created by 刘莉 on 14-10-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "MineViewController.h"
#import "MyCollectionViewController.h"
#import "AboutCarViewController.h"
#import "CollectViewController.h"
#import <MessageUI/MessageUI.h>

@interface MineViewController () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, MFMessageComposeViewControllerDelegate>

@property (nonatomic, retain)UITableView *myTableView;
@property (nonatomic, retain)NSMutableArray *arr;
@property (nonatomic, retain)NSMutableArray *arr1;
@property (nonatomic, retain)NSMutableArray *arr2;

@property (nonatomic, retain)UISlider *mySlider;
@property (nonatomic, retain)UIWindow *myWindow;
@end

@implementation MineViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.arr1 = [[NSMutableArray alloc] initWithObjects:@"清空缓存", nil];
        self.arr2 = [[NSMutableArray alloc] initWithObjects:@"评分与反馈", @"推荐给好友", nil];
        self.arr = [[NSMutableArray alloc] initWithObjects:self.arr1, self.arr2, nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupViews];
}

- (void)dealloc
{
    [_myTableView release];
    [_arr release];
    [_arr1 release];
    [_arr2 release];
    
    [super dealloc];
}

- (void)setupViews
{
    self.navigationController.navigationBar.translucent = NO;
    
    self.myTableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    self.myTableView.scrollEnabled = NO;
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    [self.view addSubview:self.myTableView];
    [_myTableView release];
}

// section个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
// section中row的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 2;
            break;
        default:
            break;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"] autorelease];
    }
   
    cell.textLabel.text = [[self.arr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    if (indexPath.section == 0 && indexPath.row == 1) {
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%.1fM", self.cachSize];
    }
       return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"将要清空缓存" message:@"请确认" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"确定", nil];
            alertView.tag = 1000;
            [alertView show];
        }
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"AppStore评分", @"意见反馈", nil];
            [alertView show];
            [alertView release];
            
        } else if (indexPath.row == 1) {
            
            // 创建信息controller
            MFMessageComposeViewController *messController = [[MFMessageComposeViewController alloc] init];
            messController.messageComposeDelegate = self;
            // 自定义信息内容
            [messController setBody:@"亲爱的朋友,我在AppStore下载了《爱尚汽车》一款坚持原创风格,为网友提供汽车报价、评测、用车、玩车等多方面的第一手资讯的车友交流应用,分享给你,速速下载吧!"];
            // 推出信息页面
            [self presentViewController:messController animated:YES completion:^{
                
            }];
            [messController release];
            
        }
    }
    // 点击cell后让cell的背景颜色快速消失
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)sliderChange:(UISlider *)slider
{
    if (slider.value == 10) {
        [self installBrightnessWindow];
        self.myWindow.hidden = NO;
        self.myWindow.alpha = 0.6;
    } else if (slider.value == 0) {
        self.myWindow.hidden = YES;
        [self.myWindow removeFromSuperview];
    }
}

- (void)installBrightnessWindow
{
    self.myWindow = [[UIWindow alloc] initWithFrame:self.view.frame];
    self.myWindow.userInteractionEnabled = NO;
    self.myWindow.backgroundColor = [UIColor grayColor];
    self.myWindow.hidden = YES;
    [_myWindow release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1000) {
        if (buttonIndex == 1) {
            dispatch_async(
                           dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                           , ^{
                               NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
                               
                               NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                               NSLog(@"files :%d",[files count]);
                               for (NSString *p in files) {
                                   NSError *error;
                                   NSString *path = [cachPath stringByAppendingPathComponent:p];
                                   if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                       [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                                   }
                               }
                               [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
        }
    } else {
    
    if (buttonIndex == 1) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"功能暂未开放" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    } else if (buttonIndex == 2) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"功能暂未开放" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    }
    }
}


-(void)clearCacheSuccess
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(106, self.view.frame.size.height - 50 - 50 - 20, 100, 50)];
    label.tag = 1100;
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor grayColor];
    label.text = @"清除成功";
    label.textAlignment = 1;
    [self.view addSubview:label];
    NSTimer *timer;
    timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(doTimer) userInfo:nil repeats:NO];
    
    
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    self.cachSize = [self folderSizeAtPath:cachPath];
    [self.myTableView reloadData];
    
}

- (void)doTimer
{
    UILabel *label = (UILabel*)[self.view viewWithTag:1100];
    [label removeFromSuperview];
    
}

//发送信息回调方法 取消->可以跳回到应用程序
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    //self.navigationController.navigationBar.translucent = NO;
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont boldSystemFontOfSize:20],NSFontAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbackground.jpg"] forBarMetrics:UIBarMetricsDefault];
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    self.cachSize = [self folderSizeAtPath:cachPath];
    [self.myTableView reloadData];
    
}

- (float)folderSizeAtPath:(NSString *)folderPath{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject])!= nil) {
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize / (1023.0 * 1024.0);
    
}

- (long long)fileSizeAtPath:(NSString *)filePath{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
